<?php
// -----------------------------------------------------------------------------
// include
// -----------------------------------------------------------------------------

include "config/config.php";
include "auth.php";

// -----------------------------------------------------------------------------
// 访问相关
// -----------------------------------------------------------------------------

if (isset($_GET['categoryId'])) {
    $categoryId = $_GET['categoryId'];
} else {
    $categoryId = 0;
}

// -----------------------------------------------------------------------------
?>
<!doctype html>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?php echo $siteTitle; ?></title>
    <link rel="stylesheet" href="resources/bootstrap-5.2.0-beta1-dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="resources/bootstrap-icons-1.5.0/bootstrap-icons.css">
    <style>
        .btnClickLink:hover {
            cursor:pointer;
            background-color: #F8F9FA;
        }
        .sidebar {
            height: calc(100vh - 48px);
            overflow-x: hidden;
            overflow-y: auto; /* Scrollable contents if viewport is shorter than content. */
        }
        .jumpToCategory:hover {
            background-color: #e5e6eb;
        }
    </style>
</head>
<body>

<!-- ----------------------------------------------------------------------- -->

<!--顶部导航栏 开始-->
<nav class="navbar navbar-dark bg-dark fixed-top">
    <div class="container-fluid">

        <!--the 菜单按钮 that 只在xs sm 屏幕上显示-->
        <button id="btnNavbarToggler" class="navbar-toggler d-block d-sm-block d-md-none" type="button">
            <span class="navbar-toggler-icon"></span>
        </button>

        <!--the 网站标题 that 显示在顶部导航栏左侧-->
        <a class="navbar-brand" href="<?php echo $homepage; ?>" target="_self"><?php echo $siteTitle; ?></a>

        <!--the 退出登录按钮 that 只在xs sm 屏幕上隐藏-->
        <p class="mt-1 mb-1 mx-2 text-white d-none d-sm-none d-md-block">
            <a href="#" class="btnLogout text-white text-decoration-none" target="_self">退出登录</a>
        </p>

    </div>
</nav>
<!--顶部导航栏 结束-->

<!-- ----------------------------------------------------------------------- -->

<div id="main"></div>

<!-- ----------------------------------------------------------------------- -->

<script src="resources/jQuery/jquery-3.5.1.js"></script>
<script src="options/option.js"></script>

<!-- ----------------------------------------------------------------------- -->

<!--全局变量-->
<script>
    const optionStrKey = "<?php echo $optionStrName; ?>"
    let optionObj = ""
    let optionStr = ""
    let categoryId = `categoryId<?php echo $categoryId; ?>`
    let sortOrder = ""
</script>

<!-- ----------------------------------------------------------------------- -->

<!--函数定义-->
<script>
    // 添加 cookie
    function setCookie(name,value,days) {
        var expires = "";
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days*24*60*60*1000));
            expires = "; expires=" + date.toUTCString();
        }
        document.cookie = name + "=" + (value || "")  + expires + "; path=/";
    }

    // 查询 cookie
    function getCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    }

    // 删除 cookie
    function eraseCookie(name) {
        document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    }

    // 动态生成网址导航数据
    function generateNav() {
        const url = "navGenerator.php";

        $.ajax({
            method: "POST",
            url: url,
            data: optionObj,
            async: false
        })
            .done(function(data) {
                $("#main").html(data)
                smoothScrollToId(categoryId)
            })
            .fail(function () {
                alert("网址导航数据请求失败！")
            });

    }

    // 平滑滚动页面到指定元素
    function smoothScrollToId(targetId) {
        const targetElement = document.getElementById(targetId);

        if (!targetElement) {
            console.error(`Element with ID "${targetId}" not found`);
            return;
        }

        // 计算偏移后的位置
        const offset = document.querySelector('.fixed-top').offsetHeight + 15; // 固定头部的高度
        const targetPosition = targetElement.getBoundingClientRect().top + window.pageYOffset - offset;

        // 使用原生方法平滑滚动
        window.scrollTo({
            top: targetPosition,
            behavior: 'smooth'
        });
    }

</script>

<!-- ----------------------------------------------------------------------- -->

<!--网页加载时自动运行-->
<script>

    $(function () {

        /* 读取用户偏好设置 */

        optionStr = localStorage.getItem(optionStrKey)

        if (optionStr == null) { // 未设定偏好
            resetOptionsStr()
            optionStr = localStorage.getItem(optionStrKey)
        }

        optionObj = JSON.parse(optionStr)

        /* 请求导航页面 */

        generateNav()

    })

</script>

<!-- ----------------------------------------------------------------------- -->

<!--事件处理-->
<script>

    // -------------------------------------------------------------------------
    // 侧边栏相关
    // -------------------------------------------------------------------------

    // 小屏幕访问时，点击顶部导航栏的「菜单」按钮，显示隐藏的分类列表
    $("#btnNavbarToggler").on("click", function (e) {
        // 隐藏右侧的退出登录按钮
        $("#navbarToggleExternalContent").hide()
        // 展开隐藏的分类列表
        $("#sidebarOnPhone").slideToggle()

        // 分类列表显示时，屏蔽或启用底部div滚动
        if ($("body").css("overflow") === "hidden") {
            $("body").css("overflow", "auto")
        } else {
            $("body").css("overflow", "hidden")
        }
    })

    // 点击(小屏幕下才显示的)分类列表上的链接时，跳转到相应锚点前，先隐藏分类列表
    $(document).on("click", ".jumpToCategoryFromPhone", function (event) {
        // 隐藏分类列表
        $(".sidebarOnPhone").hide()
        // 恢复页面滚动
        $("body").css("overflow", "auto")

        // 跳转到指定分类
        event.preventDefault();
        let targetId = this.getAttribute('href').slice(1)
        smoothScrollToId(targetId)
    })

    // 点击左侧分类导航上的链接时，跳转到相应锚点
    $(document).on("click", ".jumpToCategory", function(event) {
        // 解决问题：由于顶部导航栏使用 fixed-top 布局，页内锚点跳转位置出现偏差-
        // 参考资料：https://www.cnblogs.com/yangzhihui/p/18254448
        event.preventDefault();
        let targetId = $(this).data("href").slice(1)
        smoothScrollToId(targetId)
    })

    // -------------------------------------------------------------------------
    // 分类相关
    // -------------------------------------------------------------------------

    // 点击分类标题时，滚动页面，使得该标题在屏幕顶部显示
    $(document).on("click", ".categoryTitle", function (e) {
        const targetElementId = $(this).attr("id");
        smoothScrollToId(targetElementId)
    })

    // 获得鼠标焦点时，显示分类名右侧隐藏的置顶图标
    $(document).on("mouseenter", ".hintMoveToTop", function (e) {
        $(this).children().first().show()
    })

    // 失去鼠标焦点时，隐藏分类名右侧隐藏的置顶图标
    $(document).on("mouseleave", ".hintMoveToTop", function (e) {
        $(this).children().first().hide()
    })

    // 点击分类右侧的编辑按钮，不将分类标称移动到屏幕顶部
    $(document).on("click", ".editLinksInCategory", function(event) {
        event.stopPropagation()
    })

    // -------------------------------------------------------------------------
    // 链接相关
    // -------------------------------------------------------------------------

    // 点击导航链接，跳转到相应网站之前，先对点击事件作记录，以便统计数据
    // 当前设置下，如果后台无法访问，不能记录数据，也就不会跳转到相应网站。可以根据自己的需求改写。
    $(document).on("click", ".btnClickLink", function(e) {
        e.preventDefault()

        const linkId = $(this).data("id")
        const linkTitle = $(this).data("title")
        const linkUrl = $(this).data("url")
        const target = $(this).data("target")
        const url = "clickLog.php"

        $.ajax({
            method: "POST",
            url: url,
            async: false,
            data: { linkId: linkId, linkUrl: linkUrl, linkTitle: linkTitle }
        })
            .done(function(msg) {
                generateNav()
                window.open(linkUrl, target)
            })
            .fail(function( jqXHR, textStatus ) {
                alert("点击记录失败！")
            });
    })

    // -------------------------------------------------------------------------
    // 链接排序相关
    // -------------------------------------------------------------------------

    // 变更排序方式时执行
    $(document).on("change", ".selectLinkSortOrder", function (event) {

        let sortOrder = $(this).val()

        // 修改 json object 中相应的值
        optionObj.linkSortOrder = sortOrder

        /* json 对象转字符串，存入本地 */

        optionStr = JSON.stringify(optionObj)
        localStorage.setItem(optionStrKey, optionStr)

        // 重新加载导航页面
        generateNav()

    })

    // -------------------------------------------------------------------------
    // 其他
    // -------------------------------------------------------------------------

    // 点击底部灰色区域，跳转到屏幕顶部
    $(document).on("click", ".footer", function(event) {
        $("#back-to-top").click()
    })

    // 点击「退出登录」按钮时执行
    $(".btnLogout").on("click", function () {
        eraseCookie('<?php echo $cookieUsername; ?>');
        eraseCookie('<?php echo $cookiePassword; ?>');
        location.reload();
    });

</script>

<!-- ----------------------------------------------------------------------- -->

<!--快捷方式-->
<script>

    $(window).bind('keydown', function(event) {

        // 退出登录快捷键
        if (event.ctrlKey || event.metaKey) {
            switch ((event.key).toLowerCase()) {
                case 'o':
                    event.preventDefault();
                    $(".btnLogout")[0].click();
            }
        }

        // 快速进入分类管理界面
        switch (event.key) {
            case "i":
            case "I":
                window.location.href = "category/index.php"
        }

    });

</script>

<!-- ----------------------------------------------------------------------- -->

<!-- 添加「返回顶部按钮」 -->
<script src="resources/vanilla-back-to-top/index.js"></script>
<script src="resources/vanilla-back-to-top/config.js"></script>

<!-- ----------------------------------------------------------------------- -->

</body>
</html>
